import 'dart:async';
import 'dart:math';

import 'package:auto_route/auto_route.dart';
import 'package:casdon/core/utils/list_externtion.dart';
import 'package:extended_nested_scroll_view/extended_nested_scroll_view.dart';
import 'package:cached_network_image/cached_network_image.dart';
import 'package:casdon/app/config/theme/theme_extention.dart';
import 'package:casdon/build_gen/assets.gen.dart';
import 'package:casdon/common/utils/string_externtion.dart';
import 'package:casdon/common/widget/badge_icon.dart';
import 'package:casdon/common/widget/common_banner_widget.dart';
import 'package:casdon/common/widget/common_loading_widget.dart';
import 'package:casdon/modules/lifeCircle/application/notification/life_subject_list_notifier.dart';
import 'package:casdon/modules/lifeCircle/data/model/life_subject_module.dart';
import 'package:casdon/modules/lifeCircle/data/model/life_topic_module.dart';
import 'package:casdon/modules/lifeCircle/domain/states/life_subject_list_state.dart';
import 'package:casdon/modules/lifeCircle/domain/usecase/life_topic_list_usecase.dart';
import 'package:casdon/modules/lifeCircle/providers/life_provider.dart';
import 'package:casdon/modules/lifeCircle/ui/screen/life_topic_list_screen.dart';
import 'package:casdon/modules/recipe/ui/widgets/play_orverlay_button.dart';
import 'package:casdon/auto_router.dart';
import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';

@RoutePage()
class LifeHomeScreen extends ConsumerStatefulWidget {
  const LifeHomeScreen({super.key});

  @override
  ConsumerState<LifeHomeScreen> createState() => _LifeHomeScreenState();
}

class _LifeHomeScreenState extends ConsumerState<LifeHomeScreen>
    with TickerProviderStateMixin {
  TabController? _tabController;
  final PageController _pageController = PageController(initialPage: 1);
  final ScrollController _outerScrollController = ScrollController();

  bool _isTabChanging = false; // 防止 TabBar 和 PageView 同步时的抖动
  bool _isPageRefreshing = false; // 全局下拉刷新节流

  @override
  void initState() {
    super.initState();
    // 预热主题/数据
    Future.microtask(() {
      if (mounted) {
        ref.read(lifeSubjectListNotifierProvider(0).notifier);
      }
    });
  }

  @override
  void dispose() {
    _outerScrollController.dispose();
    _tabController?.dispose();
    super.dispose();
  }

  /// 计算并更新 TabController（科目个数变化时需重建）
  void _updateTabController(int length, {bool triggerRebuild = false}) {
    if (length <= 0) return;
    final needNew = _tabController == null || _tabController!.length != length;
    if (!needNew) return;

    // 默认选中“推荐”tab（索引1），若已存在选中则保持不变
    final oldIndex = _tabController?.index ?? 1;
    _tabController?.dispose();
    _tabController = TabController(length: length, vsync: this);

    // 尽量保持在原来的 tab（若越界则落到最后一个）
    final target = oldIndex.clamp(0, length - 1);
    _tabController!.index = target;
    if (_pageController.hasClients) {
      _pageController.jumpToPage(target);
    } else {
      WidgetsBinding.instance.addPostFrameCallback((_) {
        if (_pageController.hasClients) {
          _pageController.jumpToPage(target);
        }
      });
    }

    if (triggerRebuild && mounted) setState(() {});
  }

  /// 根据当前 Tab 求对应的 topic 列表 id
  String? _resolveCurrentSubjectId(LifeSubjectListState? subject0List) {
    final currentIndex =
        _tabController?.index ??
        (_pageController.hasClients ? _pageController.page?.round() ?? 0 : 0);

    if (currentIndex == 0) return LifeTopicListUsecase.followSubjectId;
    if (currentIndex == 1) return LifeTopicListUsecase.recommendSubjectId;

    final subjectIndex = currentIndex - 2;
    if (subject0List == null ||
        subjectIndex < 0 ||
        subjectIndex >= subject0List.data.length) {
      return null;
    }
    return subject0List.data[subjectIndex].lifeSubject?.id;
  }

  /// 整页下拉刷新：刷新 Banner/横向列表/Tab 列表 + 当前选中 Tab 的主题列表
  Future<void> _handleRefresh() async {
    if (_isPageRefreshing) return;
    _isPageRefreshing = true;
    try {
      await Future.wait([
        ref.read(lifeBannerListNotifierProvider.notifier).refresh(),
        ref.read(lifeSubjectListNotifierProvider(1).notifier).refresh(),
        ref.read(lifeSubjectListNotifierProvider(0).notifier).refresh(),
      ]);

      final subject0State = ref
          .read(lifeSubjectListNotifierProvider(0))
          .valueOrNull;
      final currentSubjectId = _resolveCurrentSubjectId(subject0State);
      if (currentSubjectId != null) {
        await ref
            .read(lifeTopicListNotifierProvider(currentSubjectId).notifier)
            .refresh();
      }
    } catch (e, st) {
      debugPrint('life_home refresh error: $e $st');
    } finally {
      _isPageRefreshing = false;
    }
  }

  @override
  Widget build(BuildContext context) {
    final bannerListState = ref.watch(lifeBannerListNotifierProvider);
    final subjectListState1 = ref.watch(lifeSubjectListNotifierProvider(1));
    final subjectListState0 = ref.watch(lifeSubjectListNotifierProvider(0));

    // 监听科目数据变化，动态创建 TabController
    ref.listen(lifeSubjectListNotifierProvider(0), (previous, next) {
      next.whenData((subject0List) {
        final totalLength = subject0List.data.length + 2; // +2: 关注/推荐
        _updateTabController(totalLength, triggerRebuild: true);
      });
    });

    final double appBarHeight = MediaQuery.of(context).padding.top + 60;

    return Scaffold(
      extendBodyBehindAppBar: true,
      backgroundColor: Colors.transparent,
      body: SafeArea(
        top: false,
        bottom: true,
        child: Stack(
          children: [
            // 顶部背景
            Positioned.fill(
              child: Image.asset(
                Assets.images.screenHeader.path,
                fit: BoxFit.cover,
                width: double.infinity,
                alignment: Alignment.topCenter,
              ),
            ),
            // 自定义 AppBar
            Positioned(
              top: 0,
              left: 0,
              right: 0,
              height: appBarHeight,
              child: _buildAppBar(context),
            ),
            Padding(
              padding: EdgeInsets.only(top: appBarHeight),
              child: RefreshIndicator(
                onRefresh: _handleRefresh,
                edgeOffset: 0,
                notificationPredicate: (notification) =>
                    notification.metrics.axis == Axis.vertical,
                child: ExtendedNestedScrollView(
                  controller: _outerScrollController,
                  onlyOneScrollInBody: true,
                  physics: const AlwaysScrollableScrollPhysics(
                    parent: BouncingScrollPhysics(),
                  ),
                  // 告知吸顶区高度（这里仅有 TabBar）
                  pinnedHeaderSliverHeightBuilder: () => 48.h,
                  headerSliverBuilder: (context, innerBoxIsScrolled) => [
                    // 顶部模块（Banner + 横向列表）
                    SliverToBoxAdapter(
                      child: Container(
                        color: Colors.transparent,
                        child: Column(
                          crossAxisAlignment: CrossAxisAlignment.start,
                          children: [
                            // Banner
                            bannerListState.when(
                              loading: () => const CommonLoadingWidget(),
                              error: (e, _) => const SizedBox.shrink(),
                              data: (state) {
                                if (state.data.isEmpty) {
                                  return SizedBox.shrink();
                                }
                                final imgUrls = state.data
                                    .map((e) => e.imageSrc.cropParams1000)
                                    .toList();
                                final linkUrls = state.data
                                    .map((e) => e.linkUrl)
                                    .toList();
                                return _buildBanner(
                                  imgUrls.takeFirstN(5),
                                  linkUrls.takeFirstN(5),
                                );
                              },
                            ),
                            // 横向列表
                            subjectListState1.when(
                              loading: () => const SizedBox.shrink(),
                              error: (e, _) => const SizedBox.shrink(),
                              data: (state) =>
                                  _buildDynamicHorizontalScrollLists(
                                    state.data,
                                  ),
                            ),
                            SizedBox(height: 16.h),
                          ],
                        ),
                      ),
                    ),

                    // 吸顶 TabBar
                    SliverPersistentHeader(
                      pinned: true,
                      delegate: _TabBarDelegate(
                        _buildTabBarContent(subjectListState0),
                        hasTabController: _tabController != null,
                      ),
                    ),
                  ],
                  // Tab 对应的页面
                  body: subjectListState0.when(
                    loading: () => const Center(child: CommonLoadingWidget()),
                    error: (e, _) => Center(child: Text('')),
                    data: (subject0List) {
                      final totalLength = subject0List.data.length + 2;
                      _updateTabController(totalLength);
                      return PageView.builder(
                        controller: _pageController,
                        itemCount: totalLength,
                        onPageChanged: (index) {
                          if (!_isTabChanging &&
                              _tabController != null &&
                              index < _tabController!.length) {
                            _isTabChanging = true;
                            _tabController!.animateTo(index);
                            Future.delayed(
                              const Duration(milliseconds: 300),
                              () {
                                if (mounted) _isTabChanging = false;
                              },
                            );
                          }
                        },
                        itemBuilder: (_, index) {
                          String subjectId;
                          if (index == 0) {
                            subjectId = LifeTopicListUsecase.followSubjectId;
                          } else if (index == 1) {
                            subjectId = LifeTopicListUsecase.recommendSubjectId;
                          } else {
                            final subjectIndex = index - 2;
                            subjectId =
                                subject0List.data[subjectIndex].lifeSubject!.id;
                          }
                          return _CachedLifeTopicListScreen(
                            key: ValueKey('life_topic_$subjectId'),
                            subjectId: subjectId,
                            isFollowTab:
                                subjectId ==
                                LifeTopicListUsecase.followSubjectId,
                            onGoExplore: () {
                              _pageController.jumpToPage(1);
                            },
                          );
                        },
                      );
                    },
                  ),
                ),
              ),
            ),
          ],
        ),
      ),
    );
  }

  Widget _buildAppBar(BuildContext context) {
    return Container(
      color: Colors.transparent,
      padding: EdgeInsets.only(
        top: MediaQuery.of(context).padding.top,
        left: 16.w,
        right: 16.w,
        bottom: 12,
      ),
      child: Row(
        children: [
          Text(
            '生活圈',
            style: context.textTheme.titleLarge!.copyWith(
              color: context.customColorThemeNonNull.textColor1,
            ),
          ),
          const Spacer(),
          BadgeIcon(
            imagePath: Assets.images.icSearch.path,
            showBadge: false,
            onPressed: () => context.router.push(const LifeSearchRoute()),
          ),
          SizedBox(width: 16.w),
          BadgeIcon(
            imagePath: Assets.images.icAddDevice.path,
            onPressed: () => context.router.push(const LifeCreatePostRoute()),
          ),
        ],
      ),
    );
  }

  Widget _buildTabBarContent(AsyncValue subjectListState0) {
    return subjectListState0.when(
      loading: () => Container(
        height: 48.h,
        alignment: Alignment.centerLeft,
        padding: EdgeInsets.only(left: 8.w),
        child: const CommonLoadingWidget(),
      ),
      error: (e, _) => Container(
        height: 48.h,
        alignment: Alignment.centerLeft,
        padding: EdgeInsets.only(left: 8.w),
        child: const SizedBox.shrink(),
      ),
      data: (subject0List) {
        final totalLength = subject0List.data.length + 2; // +2 是“关注/推荐”
        _updateTabController(totalLength);
        if (_tabController == null) {
          return Container(
            height: 48.h,
            alignment: Alignment.centerLeft,
            padding: EdgeInsets.only(left: 8.w),
            child: const CommonLoadingWidget(),
          );
        }

        final tabs = <Tab>[
          const Tab(text: '关注'),
          const Tab(text: '推荐'),
          ...subject0List.data.map<Tab>((e) => Tab(text: e.lifeSubject!.name)),
        ];

        return TabBar(
          controller: _tabController,
          isScrollable: true,
          indicatorColor: context.colorScheme.primary,
          indicatorWeight: 3.w,
          indicatorPadding: EdgeInsets.symmetric(horizontal: 8.w),
          labelColor: context.colorScheme.primary,
          unselectedLabelColor: context.customColorThemeNonNull.textColor1,
          labelStyle: context.textTheme.headlineLarge!.copyWith(
            color: context.colorScheme.primary,
          ),
          unselectedLabelStyle: context.textTheme.headlineMedium!.copyWith(
            color: context.customColorThemeNonNull.textColor1,
          ),
          labelPadding: EdgeInsets.symmetric(horizontal: 16.w),
          dividerColor: Colors.transparent,
          tabs: tabs,
          onTap: (index) {
            if (!_isTabChanging) {
              _isTabChanging = true;
              _pageController.jumpToPage(index);
              Future.delayed(const Duration(milliseconds: 300), () {
                if (mounted) _isTabChanging = false;
              });
            }
          },
        );
      },
    );
  }

  Widget _buildBanner(List<String> imageUrls, List<String> linkUrls) {
    return CommonBannerWidget(
      imageUrls: imageUrls,
      height: 148.h,
      onTap: (index) {
        if (index < 0 || index >= linkUrls.length) return;
        final urlStr = linkUrls[index];
        if (urlStr.isEmpty) return;
        context.router.push(
          WebPageRoute(url: urlStr, title: '', isFullScreen: true),
        );
      },
    );
  }

  Widget _buildDynamicHorizontalScrollLists(
    List<LifeSubjectState> lifeSubjectStates,
  ) {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        for (final subjectState in lifeSubjectStates)
          _buildHorizontalScroll(
            subjectState.lifeSubject!,
            subjectState.topicList!,
          ),
      ],
    );
  }

  Widget _buildHorizontalScroll(
    LifeSubjectModule subject,
    List<LifeTopicModule> topics,
  ) {
    return Column(
      children: [
        SizedBox(height: 24.h),
        Row(
          children: [
            SizedBox(width: 12.w),
            Text(
              subject.name,
              style: context.textTheme.headlineMedium!.copyWith(
                color: context.customColorThemeNonNull.textColor1,
              ),
            ),
            const Spacer(),
            topics.length <= 5
                ? const SizedBox.shrink()
                : TextButton(
                    style: TextButton.styleFrom(
                      padding: EdgeInsets.symmetric(
                        horizontal: 0.w,
                        vertical: 4.h,
                      ),
                      minimumSize: Size.zero,
                      tapTargetSize: MaterialTapTargetSize.shrinkWrap,
                    ),
                    onPressed: () => _goOfficialTopicListScreen(subject),
                    child: Text(
                      '更多',
                      style: context.theme.textTheme.bodyMedium!.copyWith(
                        color: context.colorScheme.primary,
                      ),
                    ),
                  ),
            SizedBox(width: 12.w),
          ],
        ),
        SizedBox(height: 12.h),
        SizedBox(
          height: 230.h,
          child: ListView.builder(
            scrollDirection: Axis.horizontal,
            padding: EdgeInsets.symmetric(horizontal: 12.w),
            itemCount: min(topics.length, 5),
            itemBuilder: (_, index) => Container(
              width: 160.w,
              margin: EdgeInsets.only(left: 0.w, right: 12.w),
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.center,
                children: [
                  SizedBox(
                    width: double.infinity,
                    height: 180.h,
                    child: ClipRRect(
                      borderRadius: BorderRadius.circular(8),
                      child: Stack(
                        fit: StackFit.expand,
                        children: [
                          CachedNetworkImage(
                            imageUrl: topics[index].coverImg,
                            cacheKey: topics[index].id,
                            fit: BoxFit.cover,
                            fadeInDuration: Duration.zero,
                            placeholder: (context, url) => const SizedBox(),
                            errorWidget: (context, url, error) =>
                                const Icon(Icons.error, color: Colors.red),
                          ),
                          if (topics[index].mediaType ==
                              LifeTopicMediaType.video)
                            PlayOverlayButton(
                              onTap: () => _handleVideoTap(
                                context,
                                topics[index].mediaSrcList[0],
                              ),
                            ),
                        ],
                      ),
                    ),
                  ),
                  SizedBox(height: 6.h),
                  Padding(
                    padding: EdgeInsets.only(left: 4.w),
                    child: GestureDetector(
                      onTap: () => _handleItemClick(topics[index]),
                      child: SizedBox(
                        width: 160.w,
                        child: Text(
                          topics[index].title,
                          textAlign: TextAlign.left,
                          maxLines: 2,
                          overflow: TextOverflow.ellipsis,
                          style: context.textTheme.bodyMedium!.copyWith(
                            color: context.customColorThemeNonNull.textColor1,
                          ),
                        ),
                      ),
                    ),
                  ),
                ],
              ),
            ),
          ),
        ),
      ],
    );
  }

  void _goOfficialTopicListScreen(LifeSubjectModule subject) {
    context.router.push(
      LifeOfficialTopicListRoute(subjectId: subject.id, title: subject.name),
    );
  }

  void _handleItemClick(LifeTopicModule item) {
    context.router.push(LifeTopicDetailRoute(topicId: item.id));
  }

  void _handleVideoTap(BuildContext context, String mediaSrcList) {
    context.router.push(VideoPlayerRoute(url: mediaSrcList, title: ''));
  }
}

class _TabBarDelegate extends SliverPersistentHeaderDelegate {
  final Widget _tabBar;
  final bool hasTabController;

  _TabBarDelegate(this._tabBar, {this.hasTabController = false});

  @override
  double get minExtent => 48.0.h;

  @override
  double get maxExtent => 48.0.h;

  @override
  Widget build(
    BuildContext context,
    double shrinkOffset,
    bool overlapsContent,
  ) {
    return OverflowBox(
      minWidth: MediaQuery.of(context).size.width,
      maxWidth: MediaQuery.of(context).size.width + 48.w,
      alignment: Alignment.centerLeft,
      child: Transform.translate(offset: Offset(-48.w, 0), child: _tabBar),
    );
  }

  @override
  bool shouldRebuild(_TabBarDelegate oldDelegate) =>
      oldDelegate._tabBar != _tabBar ||
      oldDelegate.hasTabController != hasTabController;
}

/// 缓存版本的 LifeTopicListScreen，保持页面状态，避免切换 tab 时重新加载
class _CachedLifeTopicListScreen extends ConsumerStatefulWidget {
  final String subjectId;
  final bool? isFollowTab;
  final VoidCallback? onGoExplore;

  const _CachedLifeTopicListScreen({
    super.key,
    required this.subjectId,
    this.isFollowTab,
    this.onGoExplore,
  });

  @override
  ConsumerState<_CachedLifeTopicListScreen> createState() =>
      _CachedLifeTopicListScreenState();
}

class _CachedLifeTopicListScreenState
    extends ConsumerState<_CachedLifeTopicListScreen>
    with AutomaticKeepAliveClientMixin {
  @override
  bool get wantKeepAlive => true;

  @override
  Widget build(BuildContext context) {
    super.build(context);
    // 交由 ExtendedNestedScrollView 管理滚动；上拉加载通过外层 NotificationListener 触发
    return LifeTopicListScreen(
      subjectId: widget.subjectId,
      controller: null,
      isFollowTab: widget.isFollowTab,
      onGoExplore: widget.onGoExplore,
    );
  }
}
